const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const app = express();
const PORT = 3001;

app.use(cors());
app.use(express.json());

// 获取所有唐诗，支持搜索
app.get('/api/tang-poems', (req, res) => {
  const db = new sqlite3.Database('./tang_poems.db');
  const q = req.query.q;
  let sql = 'SELECT * FROM tang_poems';
  let params = [];
  if (q) {
    // 多关键字支持，空格分隔，全部AND
    const keywords = q.trim().split(/\s+/);
    const wheres = keywords.map(() => '(title LIKE ? OR content LIKE ? OR author LIKE ?)');
    sql += ' WHERE ' + wheres.join(' AND ');
    params = keywords.flatMap(k => [`%${k}%`, `%${k}%`, `%${k}%`]);
  }
  console.log('SQL:', sql, params);
  db.all(sql, params, (err, rows) => {
    db.close();
    if (err) {
      res.status(500).json({ error: err.message });
    } else {
      // 将 content 字段按句号、问号、感叹号、分号分割为数组，便于前端兼容
      const poems = rows.map(poem => ({
        ...poem,
        dynasty: poem.dynasty || '唐', // 确保有朝代信息
        verses: poem.content.replace(/[。！？；]/g, '$&|').split('|').map(s => s.trim()).filter(Boolean)
      }));
      res.json(poems);
    }
  });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
}); 